<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 获取原始输入
    $rawInput = file_get_contents("php://input");

    // 检查是否为空
    if (empty($rawInput)) {
        echo json_encode(array("status" => "error", "message" => "未收到任何输入数据"));
        exit;
    }

    // 尝试解析 JSON
    $data = json_decode($rawInput, true);

    // 验证解析是否成功
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo json_encode(array("status" => "error", "message" => "JSON 数据解析失败"));
        exit;
    }

    // 验证字段
    if (empty($data['username']) || empty($data['password'])) {
        echo json_encode(array("status" => "error", "message" => "所有字段均为必填项"));
        exit;
    }

    $username = trim($data['username']);
    $password = trim($data['password']);

    // 连接数据库
    $conn = new mysqli('localhost', 'root', '', 'test');

    if ($conn->connect_error) {
        echo json_encode(array("status" => "error", "message" => "数据库连接失败"));
        exit;
    }

    // 查询用户
    $sql = "SELECT id, password FROM student WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password'])) {
            echo json_encode(array("status" => "success", "data" => array("user_id" => $user['id'])));
        } else {
            echo json_encode(array("status" => "error", "message" => "密码错误"));
        }
    } else {
        echo json_encode(array("status" => "error", "message" => "用户不存在，请注册"));
    }

    $stmt->close();
    $conn->close();
} else {
    echo json_encode(array("status" => "error", "message" => "请求方式错误"));
}
?>
